// Display last status changed model for Google App Engine Channel API

var socket = "";
var isInitialized = false;
var isConnected = false;


function onOpened(){
//	alert("接続が開始されました。データを送信できます");
    isConnected = true;
    sendMessage("init", "");
}
 
function onMessage(message){
//    alert("serverから「" + message.data + "」を受け取りました");
    var json = eval("(" + message.data + ")");

    redrawContentsMenu(json);
}
 
function onError(error){
//	alert("serverでエラーが起きました。description=" + error.description + "。code=" + error.code);
}
 
function onClose(){
//	alert("接続が正常に終了しました");
    isConnected = false;
    isInitialized = false;
}


function createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId) {
    if (obj == "") {
    	return false;
    }

    size = obj.length;
    if (size == 0) {
    	return false;
    }

	childUl = document.createElement('ul');
    for (i = 0; i < size; i++) {
    	id = obj[i].id;
    	name = obj[i].name;
    	 
    	childImg = document.createElement('img');
    	if (obj[i].id == lastUpdatedForLendingId) {
    		childImg.setAttribute("src", "/tmserver/img/attention_model.png");
    	} else {
    		childImg.setAttribute("src", "/tmserver/img/normal_model.png");
    	}

    	childSpan = document.createElement('span');
    	childSpan.innerHTML = childImg.outerHTML + name;

    	childLi = document.createElement('li');
    	childLi.appendChild(childSpan);

    	childUl.appendChild(childLi);
    }
    parentElement = document.createElement('li');
    parentElement.innerHTML = title + childUl.outerHTML;

    rootElement.appendChild(parentElement);
    
    return true;
}
	
function createContentsNodesCount(obj, rootElement, title) {
    if (obj == "") {
    	return false;
    }
	childUl = document.createElement('ul');
	count = obj;
    if (parseInt(obj) == 0) {
    	return false;
    }

	childImg = document.createElement('img');
	childImg.setAttribute("src", "/tmserver/img/normal_model.png");

	childSpan = document.createElement('span');
	childSpan.innerHTML = childImg.outerHTML + "現在貸し出し中の物品数 : " + count;

	childLi = document.createElement('li');
	childLi.appendChild(childSpan);

	childUl.appendChild(childLi);

    parentElement = document.createElement('li');
    parentElement.innerHTML = title + childUl.outerHTML;

    rootElement.appendChild(parentElement);
    
    return true;
}
	
function redrawContentsMenu(json) {
    /*
    if (json.lastUpdatedLendingHistoryId != "") {
	    mes = json.lastUpdatedLendingHistoryId;
	    alert("「" + mes + "」");
	}
    if (json.lastUpdatedForLendingId != "") {
	    mes = json.lastUpdatedForLendingId;
	    alert("「" + mes + "」");
	}

    if (json.lendingMisyounin != "") {
        mes = json.lendingMisyounin.length;
        for (i = 0; i < json.lendingMisyounin.length; i++) {
        	mes = mes + " " + json.lendingMisyounin[i].name;
        }
        alert("「" + mes + "」");
	}
    if (json.lendingSyouninzumi != "") {
        mes = json.lendingSyouninzumi.length;
        for (i = 0; i < json.lendingSyouninzumi.length; i++) {
        	mes = mes + " " + json.lendingSyouninzumi[i].name;
        }
        alert("「" + mes + "」");
	}
    if (json.lendingKashidasityuCount != "") {
	    mes = json.lendingKashidasityuCount;
	    alert("「" + mes + "」");
	}

    if (json.borrowingMisyounin != "") {
        mes = json.borrowingMisyounin.length;
        for (i = 0; i < json.borrowingMisyounin.length; i++) {
        	mes = mes + " " + json.borrowingMisyounin[i].name;
        }
        alert("「" + mes + "」");
	}
    if (json.borrowingSyouninzumi != "") {
        mes = json.borrowingSyouninzumi.length;
        for (i = 0; i < json.borrowingSyouninzumi.length; i++) {
        	mes = mes + " " + json.borrowingSyouninzumi[i].name;
        }
        alert("「" + mes + "」");
	}
    if (json.borrowingKashidasityu != "") {
        mes = json.borrowingKashidasityu.length;
        for (i = 0; i < json.borrowingKashidasityu.length; i++) {
        	mes = mes + " " + json.borrowingKashidasityu[i].name;
        }
        alert("「" + mes + "」");
	}
    if (json.borrowingShinseikyakka != "") {
        mes = json.borrowingShinseikyakka.length;
        for (i = 0; i < json.borrowingShinseikyakka.length; i++) {
        	mes = mes + " " + json.borrowingShinseikyakka[i].name;
        }
        alert("「" + mes + "」");
	}
*/

	// last updated
	lastUpdatedLendingHistoryId = -1;
	idString = json.lastUpdatedLendingHistoryId;
	if (idString != "") {
		lastUpdatedLendingHistoryId = parseInt(idString);
	}
	lastUpdatedForLendingId = -1;
	idString = json.lastUpdatedForLendingId;
	if (idString != "") {
		lastUpdatedForLendingId = parseInt(idString);
	}
	
	hasList = false;
	rootElement = document.getElementById("lendingList");
	rootElement.innerHTML = "";

	// lending: Misyounin
	obj = json.lendingMisyounin;
	title = "承認待ちリスト";
	result = createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId);
	if (result) {
		hasList = true;
	}
	
	// lending: Syouninzumi
	obj = json.lendingSyouninzumi;
	title = "貸出予約済みリスト";
	result = createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId);
	if (result) {
		hasList = true;
	}

	// lending: KashidasityuCount
	obj = json.lendingKashidasityuCount;
	title = "貸出中件数";
	result = createContentsNodesCount(obj, rootElement, title);
	if (result) {
		hasList = true;
	}

	// borrowing: Misyounin
	obj = json.borrowingMisyounin;
	title = "借入申込み中リスト";
	result = createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId);
	if (result) {
		hasList = true;
	}

	// borrowing: Syouninzumi
	obj = json.borrowingSyouninzumi;
	title = "借入予約中リスト";
	result = createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId);
	if (result) {
		hasList = true;
	}

	// borrowing: Kashidasityu
	obj = json.borrowingKashidasityu;
	title = "借入中リスト";
	result = createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId);
	if (result) {
		hasList = true;
	}

	// borrowing: Shinseikyakka
	obj = json.borrowingShinseikyakka;
	title = "借入申込み却下リスト（過去１０日分）";
	result = createContentsNodesModel(obj, rootElement, title, lastUpdatedLendingHistoryId, lastUpdatedForLendingId);
	if (result) {
		hasList = true;
	}

	if (hasList) {
		titleElement = document.getElementById("lendingListTitle");
	    currentClass = titleElement.getAttribute("class");
	    titleElement.setAttribute("class", currentClass.replace("NoDisp", "Disp"));
		
	    currentClass = rootElement.getAttribute("class");
	    rootElement.setAttribute("class", currentClass.replace("NoDisp", "Disp"));
	}
	
}

function sendMessage(command, message) {
    if (isInitialized == false) {
    	//alert("初期化が終わっていないのでデータを送信できません。数秒後に再度送信してください");
        return;
    }
    if (isConnected == false) {
    	//alert("接続が完了していないのでデータを送信できません。数秒後に再度送信してください");
        return;
    }

    var http = new XMLHttpRequest();

    path = '/tmserver/channel/receiveMessage' 
    	+ '?command=' + command 
    	+ '&userId=' + userId 
    	+ '&message=' + message;
    http.open('POST', path);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    http.send();
//    alert("「" + command + ":" + message + "」" + "を送信しました");
}

function closeSocket(){
    if (socket == "" || isInitialized == false || isConnected == false) {
    	//alert("まだ接続されていません");
        return;
    }
 
    socket.close();
    socket = "";
    isInitialized = false;
    isConnected = false;
//    alert("接続を終了しました");
}


function initialize() {
	if (typeof token == "undefined") {
		return;
	}

	if (isInitialized == true) {
        //alert("既に初期化済みです");
        return;
    }
    if (isConnected == true) {
        //alert("既に接続済みです");
        return;
    }

    channel = new goog.appengine.Channel(token);
    socket = channel.open();
    socket.onopen = onOpened;
    socket.onmessage = onMessage;
    socket.onerror = onError;
    socket.onclose = onClose;
    isInitialized = true;

//    alert("初期化が完了しました。serverからの応答待ちです");
}

if (window.addEventListener) {
	window.addEventListener('load', initialize, false);
} else if (window.attachEvent) {
	window.attachEvent('onload', initialize);
} else {
	//window.onload = initialize;
}
